import api from "../../api/axios";
import React, { useEffect, useState } from "react";
import { Tabs } from "antd-mobile";
import { Button, Space, Table, Modal, Form, Input } from "antd";
import type { TableProps } from "antd";
import { useNavigate } from "react-router-dom";

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

type FieldType = {
  content?: string;
  title?: string;
  remember?: string;
};

function Index() {
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(1);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [title, setTitle] = useState("");
  const [tit, setTit] = useState("");
  const [editid, setEditid] = useState("");
  const navigate = useNavigate();
  const getData = async (title: string) => {
    const res = await api.get("/article/list", {
      params: {
        page, //页码
        pageSize, //每页显示条数
        keyword: title, //搜索标题
      },
    });
    console.log(res);
    setList(res.data.rows);
    setTotal(res.data.count);
  };
  const goDetail = (id) => {
    navigate(`/detail/${id}`);
  };
  useEffect(() => {
    getData();
  }, []);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const showModal = () => {
    setIsModalOpen(true);
    form.resetFields();
    setTit(true);
  };
  const edit = (record) => {
    setIsModalOpen(true);
    form.setFieldsValue(record);
    setTit(false);
    setEditid(record.id);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish: FormProps<FieldType>["onFinish"] = async (values) => {
    console.log("Success:", values);
    if (tit) {
      const res = await api.post("/article", {
        ...values,
        authorId: 47529555,
      });
      getData();
      setIsModalOpen(false);
    } else {
      const res = await api.put(`/article/${editid}`, values);
      getData();
      setIsModalOpen(false);
    }
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "Id",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "Title",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "Content",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "UpdatedAt",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button>删除</Button>
          <Button onClick={() => edit(record)}>编辑</Button>
          <Button onClick={() => goDetail(record.id)}>详情</Button>
        </Space>
      ),
    },
  ];
  return (
    <div>
      <Tabs>
        <Tabs.Tab title="全部" key="fruits">
          <div>
            <div>
              <Button type="primary" onClick={showModal}>
                新增
              </Button>
              <Modal
                title={tit ? "新增" : "编辑"}
                closable={{ "aria-label": "Custom Close Button" }}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
              >
                <Form
                  form={form}
                  name="basic"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                  style={{ maxWidth: 600 }}
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                >
                  <Form.Item<FieldType>
                    label="Title"
                    name="title"
                    rules={[
                      {
                        required: true,
                        message: "Please input your username!",
                      },
                    ]}
                  >
                    <Input />
                  </Form.Item>

                  <Form.Item<FieldType>
                    label="Content"
                    name="content"
                    rules={[
                      {
                        required: true,
                        message: "Please input your password!",
                      },
                    ]}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item label={null}>
                    <Button type="primary" htmlType="submit">
                      提交
                    </Button>
                  </Form.Item>
                </Form>
              </Modal>
            </div>
            <div>
              <Table<DataType>
                columns={columns}
                rowKey="id"
                dataSource={list}
              />
            </div>
          </div>
        </Tabs.Tab>
        <Tabs.Tab title="咨询" key="vegetables">
          咨询
        </Tabs.Tab>
        <Tabs.Tab title="MCP" key="animals">
          MCP
        </Tabs.Tab>
      </Tabs>
    </div>
  );
}

export default Index;
